<template>
  <el-card shadow="hover" class="mt-20">
    <el-form label-width="100px" ref="spuFormRef" :model="spuFormData" :rules="spuFormRules">
      <el-form-item label="SPU名称" prop="spuName">
        <el-input placeholder="请输入SPU名称" v-model="spuFormData.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌" prop="tmId">
        <el-select placeholder="请选择品牌" v-model="spuFormData.tmId">
          <el-option v-for="tm in trademarkList" :key="tm.id" :label="tm.tmName" :value="tm.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述" prop="description">
        <el-input type="text" placeholder="请输入SPU描述" v-model="spuFormData.description" :rows="3"></el-input>
      </el-form-item>
      <el-form-item label="SPU图片" prop="spuImageList">
        <el-upload
          v-model:file-list="spuFormData.spuImageList"
          :action="`${BASE_URL}/admin/product/upload`"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :before-upload="beforeAvatarUpload"
          :limit="MAX_UPLOAD_LIMIT"
          :on-exceed="handleExceed"
          accept="image/jpeg, image/png"
          :on-success="handelUploadSuccess"
        >
          <el-icon>
            <Plus />
          </el-icon>

          <template #tip>
            <div class="el-upload__tip">只能上传jpg/png文件，且不超过200kb</div>
          </template>
        </el-upload>

        <el-dialog v-model="dialogVisible" width="30%">
          <img :src="dialogImageUrl" alt="预览图片" class="spu__img" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性" prop="spuSaleAttrList">
        <el-select placeholder v-model="selectedBaseSaleAttr">
          <el-option
            v-for="baseSaleAttr in filteredBaseSaleAttrList"
            :key="baseSaleAttr.id"
            :label="baseSaleAttr.name"
            :value="`${baseSaleAttr.id}:${baseSaleAttr.name}`"
          ></el-option>
        </el-select>
        <el-button type="primary" :icon="Plus" @click="addSaleAttr">添加销售属性</el-button>
        <el-table :data="spuFormData.spuSaleAttrList" border class="mt-20">
          <el-table-column label="序号" type="index" align="center" width="60"></el-table-column>
          <el-table-column label="属性名" prop="saleAttrName"></el-table-column>
          <el-table-column label="属性值名称列表">
            <template v-slot="{ row }">
              <el-tag
                type="success"
                v-for="(spuSaleAttrValue, index) in row.spuSaleAttrValueList"
                :key="spuSaleAttrValue.saleAttrValueName"
                class="mr-10"
                closable
                @close="delSpuSaleAttrValue(row.spuSaleAttrValueList, index)"
              >{{ spuSaleAttrValue.saleAttrValueName }}</el-tag>
              <el-input
                @blur="addAttrValue(row)"
                @keyup.enter="addAttrValue(row)"
                v-model="saleAttrValueName"
                size="small"
                v-if="row.isShowEdit"
                ref="inputRef"
                class="spu__input--w-150"
              ></el-input>
              <el-button :icon="Plus" size="small" v-else @click="switchEdit(row)"></el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row, $index }">
              <el-button type="danger" size="small" :icon="Delete" @click="delSaleAttr($index)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label>
        <el-button type="primary" @click="submit">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "addSpu",
};
</script>

<script lang="ts" setup>
import { Plus, Delete } from "@element-plus/icons-vue";
import { ref, reactive, computed, onMounted, nextTick } from "vue";
import { ElMessage, inputEmits } from "element-plus";
import type { UploadProps } from "element-plus";
import { getAllTrademarkListApi } from "@/api/product/trademark";
import {
  getBaseSaleAttrListApi,
  addSpuApi,
  getSpuImageListApi,
  getSpuSaleAttrListApi,
  updateSpu
} from "@/api/product/spu";
import type {
  BaseSaleAttrList,
  SpuFormData,
  SpuSaleAttrItem,
  SpuSaleAttrValueList,
  SpuSaleAttrList,
} from "@/api/product/model/spuModel";
import { useSpuStore } from "@/stores/spu";
import type { TrademarkList } from "@/api/product/model/trademarkModel";
import { useCategoryStore } from "@/stores/category";
const trademarkList = ref<TrademarkList>([]);
const baseSaleAttrList = ref<BaseSaleAttrList>([]);
onMounted(async () => {
  trademarkList.value = await getAllTrademarkListApi();
});
onMounted(async () => {
  baseSaleAttrList.value = await getBaseSaleAttrListApi();
});
onMounted(async() =>{
  const id = spuStore.spu.id as number;
  if(!id) return 

  const spuImageList = await getSpuImageListApi(id);
  spuFormData.spuImageList = spuImageList.map((img)=>{
    return {
      name:img.imgName,
      url:img.imgUrl,
      response:{
        data:img.imgUrl
      }
    }
  })
})
onMounted(async()=>{
  const id = spuStore.spu.id as number
  if(!id) return 
  spuFormData.spuSaleAttrList = await getSpuSaleAttrListApi(id)
})
const categoryStore = useCategoryStore();

//提交表单
const submit = async () => {
  await spuFormRef.value.validate();
  const id = spuStore.spu.id
  const data = {
    category3Id: categoryStore.category3Id,
    ...spuFormData,
    spuImageList: spuFormData.spuImageList.map((img) => {
      return {
        imgName: img.name,
        imgUrl: (img.response as { data: string }).data,
      };
    }),
  }
  if(id){
    await updateSpu({
      ...data,
      id
    })
  }else{
    await addSpuApi(data)
  }
  ElMessage.success("添加成功");
  cancel();
};
//图片上传成功清空效验错误信息
const handelUploadSuccess = () => {
  spuFormRef.value.clearValidate(["spuImageList"]);
};

const inputRef = ref();
const saleAttrValueName = ref("");
const isEditing = ref(false);

//失去焦点或回车是添加属性值
const addAttrValue = (row: SpuSaleAttrItem) => {
  if (
    row.spuSaleAttrValueList.some(
      (spuSaleAttrValue) =>
        spuSaleAttrValue.saleAttrValueName === saleAttrValueName.value
    )
  ) {
    ElMessage.warning("请不要输入相同的值");
    return;
  }
  isEditing.value = false;
  row.isShowEdit = false;
  if (!saleAttrValueName.value) return;

  row.spuSaleAttrValueList.push({
    baseSaleAttrId: row.baseSaleAttrId,
    saleAttrValueName: saleAttrValueName.value,
  });
  saleAttrValueName.value = "";
};

//显示编辑模式
const switchEdit = async (row: SpuSaleAttrItem) => {
  if (isEditing.value) {
    ElMessage.warning("请完成之前的编辑");
    return;
  }
  isEditing.value = true;
  row.isShowEdit = true;
  await nextTick(); //放到异步队列
  inputRef.value.focus(); //获取焦点
};

//过滤点 添加过的属性
const filteredBaseSaleAttrList = computed(() => {
  return baseSaleAttrList.value.filter((baseSaleAttr) => {
    if (
      spuFormData.spuSaleAttrList.some(
        (spuSaleAttr) => spuSaleAttr.baseSaleAttrId === baseSaleAttr.id
      )
    ) {
      // 在，过滤
      return false;
    }
    // 不在，保留
    return true;
  });
});

const selectedBaseSaleAttr = ref("");

//添加销售属性
const addSaleAttr = () => {
  const [id, name] = selectedBaseSaleAttr.value.split(":");
  spuFormData.spuSaleAttrList.push({
    baseSaleAttrId: +id,
    saleAttrName: name,
    spuSaleAttrValueList: [],
    isShowEdit: false,
  });
  selectedBaseSaleAttr.value = "";
};

//删除属性
const delSaleAttr = (index: number) => {
  console.log(index);
  spuFormData.spuSaleAttrList.splice(index, 1);
};

//图片预览
const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url as string;
  dialogVisible.value = true;
};

//效验图片
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const fileType = ["image/jpeg", "image/png"];
  if (!fileType.includes(rawFile.type)) {
    ElMessage.error("上传图片格式不正确");
    return false;
  } else if (rawFile.size / 1024 > 200) {
    ElMessage.error("图片不能大于200kb");
    return false;
  }
  return true;
};

const MAX_UPLOAD_LIMIT = 2;

const handleExceed = () => {
  ElMessage.warning(`图片最多上传${MAX_UPLOAD_LIMIT}张`);
};

//  上传图片的显示与隐藏
const isUploadHidden = computed(() => {
  return spuFormData.spuImageList.length < MAX_UPLOAD_LIMIT
    ? "inline-flex"
    : "none";
});

//图片上传
const BASE_URL = import.meta.env.VITE_API_URL;

const spuStore = useSpuStore();
//表单效验
const spuFormRef = ref();
const spuFormData = reactive<SpuFormData>({
  spuName: spuStore.spu.spuName,
  tmId: spuStore.spu.tmId,
  description: spuStore.spu.description,
  spuImageList: [],
  spuSaleAttrList: [],
});
const spuSaleAttrListValidator = (
  rule: any,
  value: SpuSaleAttrList,
  callback: any
) => {
  if (!value.length) {
    callback(new Error("请至少添加一个销售属性"));
    return;
  }

  if (value.some((spuSaleAttr) => !spuSaleAttr.spuSaleAttrValueList.length)) {
    callback(new Error("每个销售属性请至少添加一个销售属性值"));
    return;
  }
  callback();
};

const spuFormRules = reactive({
  spuName: [{ required: true, message: "请输入SPU名称", trigger: "blur" }],
  tmId: [{ required: true, message: "请选择品牌", trigger: "change" }],
  description: [{ required: true, message: "请输入SPU描述", trigger: "blur" }],
  spuImageList: [{ required: true, message: "请上传SPU图片" }],
  spuSaleAttrList: [{ required: true,validator:spuSaleAttrListValidator }],
});


const emit = defineEmits(["setIsShow"]);

const cancel = () => {
  emit("setIsShow", 1);
};
</script>

<style scoped>
:deep(.el-upload) {
  display: v-bind(isUploadHidden);
}
.spu__input--w-150 {
  width: 150px;
}
</style>
